const svc = require('../util/service'),
log = require('../util/log'),
url = require('url'),
http = require('http'),
iconv = require('iconv-lite'),
xml2js = require('xml2js');

module.exports = (req, res) => {
	svc.handleGet(req, res, (reqObj, resolve) => {
		if (!reqObj.url) {
			resolve({
				result: -1,
				msg: '缺少url'
			})
			return
		}
		reqObj.url = decodeURIComponent(reqObj.url);
		const parsedUrl = url.parse(reqObj.url, true),
		options = {
			host: parsedUrl.hostname,
			port: parsedUrl.port,
			path: parsedUrl.pathname + parsedUrl.search,
			method: 'GET'
		}
		const req = http.request(options, (res) => {
				var body = []
				res.on('data', (chunk) => {
					body.push(chunk)
				}).on('end', () => {
					var html = Buffer.concat(body).toString(),
					start = 0,
					end,
					xml,
					_start;
					while ((start = html.indexOf('<?xml', start)) != -1) {
						end = html.indexOf('?>', start) + 2;
						xml = html.substring(start, end);
						_start = xml.indexOf('encoding=');
						if (_start != -1) {
							_start += 9;
							if (xml.substring(_start, _start + 1) == '"')
								_start++;
							if (xml.substring(_start, _start + 6) == 'gb2312') {
								html = iconv.decode(Buffer.concat(body), 'GBK');
								break
							}
						}
						start += xml.length
					}
					xml2js.parseString(html, (err, result) => {
						result.rss.channel.length > 1 && log(reqObj.url + '有多个channel')
						resolve({
							result: 1,
							rss: result.rss.channel[0].item
						})
					})
				}).on('error', (err) => {
					log(err)
				})
			});
		req.on('error', (err) => {
			log(err)
			resolve({
				result: -1,
				msg: '获取html失败'
			})
		});
		req.end()
	})
}
